package com.google.code.hibernate.rest.method;
import static java.net.HttpURLConnection.HTTP_OK;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.code.hibernate.rest.EntityManager;

/**
 * 
 * @author wangzijian
 * 
 */
public class OptionsMethodProcessor extends AbstractMethodProcessor {

	public static final String HEADER_ALLOW = "Allow";

	public OptionsMethodProcessor(EntityManager entityManager) {
		super(entityManager);
	}

	@Override
	protected void doProcess(URIMatchMode matchMode, HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setHeader(HEADER_ALLOW, getAllowOptions(request.getPathInfo()));
		response.setStatus(HTTP_OK);
	}

	public String getAllowOptions(String uri) {
		URIMatchMode matchMode = URIMatchMode.matchs(uri);
		List<String> allowMethods = matchMode.getAllowMethods(uri, entityManager);
		return joinOnComma(allowMethods);
	}

	private String joinOnComma(List<String> list) {
		StringBuilder sb = new StringBuilder();
		Iterator<String> iterator = list.iterator();
		if (iterator.hasNext()) {
			sb.append(iterator.next());
			while (iterator.hasNext()) {
				sb.append(", ");
				sb.append(iterator.next());
			}
		}
		return sb.toString();
	}
}
